<template>
  <div id="dtools_find_my">

    <SettingComponent
        id="setting"
    />

    <!-- LOGO -->
    <LogoComponent
        id="logo"
        :logo-mode="logo.mode"
        :logo-text="logo.text"
    />

    <!-- 搜索输入框 -->
    <SearchInputComponent
        id="search_input"
        :searchList="searchList"
        :aiChatRecordList="aiChatRecordList"
        :aiChatRecordShow="aiChatRecordShow"
        ref="searchInputComponentRef"
        @change:engine="changeEngine"
        @confirm:input="confirmInput"
        @change:input="changeInput"
        @confirm:select="confirmSelect"
        @click:blank="clickBlank"
    />

    <!-- 收藏网页站点 -->
    <FavoriteWebComponent
        id="favorite_web"
        :favoriteWebList="favoriteWebList"
        @change:favorite="changeFavorite"
        @skip:folder="skipFolder"
    />

  </div>
</template>

<script>

import {marked} from 'marked';
import LogoComponent from './components/LogoComponent.vue'
import SettingComponent from './components/SettingComponent.vue'
import SearchInputComponent from './components/SearchInputComponent.vue'
import FavoriteWebComponent from './components/FavoriteWebComponent.vue'
import ClockComponent from './components/ClockComponent.vue'
import LocalFileSendComponent from './components/LocalFileSendComponent.vue'
import AiService from '../service/aiService.js'
import LightTextUtil from '../utils/lightTextUtil.js'
import FinderIQService from '../service/finderIQService.js'

import waitIcon from '@/assets/images/system/wait.gif';

export default {
  components: {
    LogoComponent, SettingComponent, SearchInputComponent, FavoriteWebComponent, ClockComponent, LocalFileSendComponent
  },
  data() {
    return {
      chromeExtensionModel: false,
      // 主页LOGO设置
      logo: {mode: "text", text: "FinderIQ"},
      // 首页收藏站点
      favoriteWebList: [],
      // 浏览器书签站点
      bookmarkList: [],
      // 搜索出内容列表
      searchList: [],
      // AI 回复内容
      aiChatRecordShow: false,
      aiChatRecordList: []
    }
  },
  computed: {
  },
  methods: {
    // 搜索引擎变更
    changeEngine(value) {
      if (value !== 'ai') {
        this.aiChatRecordShow =  false;
        this.aiChatRecordList = [];
      }
    },
    // 输入确认
    confirmInput(event) {
      if (event.value === '') {
        return
      }
      const searchUrls = {
        baidu: 'https://www.baidu.com/s?wd=', biying: 'https://cn.bing.com/search?q=',
        ai: 'https://cn.bing.com/search?q=', google: 'https://www.google.com/search?q='
      };

      if (event.engine === 'ai' && !event.altKey) {
        this.searchList = []
        // 清除子组件的输入框
        this.$refs.searchInputComponentRef.clearInput();
        this.$refs.searchInputComponentRef.aiGenerateStart();
        this.aiChatRecordShow = true;
        this.aiChatRecordList.push({
          question: event.value,
          answer: "",
          readNetData: "",
          searchContentFlag: false,
          searchLoading: false,
          answerLoading: true
        })
        this.aiChat(event.value);
      } else {
        const engine = event.engine === 'ai' ? 'biying' : event.engine;
        window.open(searchUrls[engine] + event.value, '_blank');
      }
    },
    // 输入变更
    changeInput(event) {
      // 去除空格
      const contentStr = event.value.trim();
      console.log("检索:", contentStr)
      console.log("检索:", this.aiChatRecordList.length)
      // 清空检索列表
      this.searchList = [];
      // 如果值为空，则不进行搜索
      if (contentStr.length >= 25 || this.aiChatRecordList.length > 0) return;

      // 对搜索的内容去除空格并进行语义切割，得到数组
      const cutStrList = this.statementCutting(contentStr);
      // 检索收藏站点
      this.searchList.push(...this.matchSearchInput(this.favoriteWebList, cutStrList, 'favorite'))
      // 检索书签站点
      this.getBookmarkList();
      this.searchList.push(...this.matchSearchInput(this.bookmarkList, cutStrList, 'bookmark'))
    },
    // 文本块截切
    statementCutting(contentStr) {
      const searchContent = contentStr.trim();
      // 二次切割
      let searchContentList = []
      // 按照类型切割
      const searchContents = searchContent.match(/[a-zA-Z]+|[\u4e00-\u9fa5]+|\d+|\W+/g) || [];
      // console.log("一次切割:", searchContents)

      searchContents.forEach(item => {
        // 如果当前字符串为中文，则进行二次切割程序
        const chineseRegex = /[\u4e00-\u9fa5]/;
        if (chineseRegex.test(item)) {
          searchContentList.push(...item.split(''))
        } else if (item.includes(' ')) {
          searchContentList.push(...item.split(' '))
        } else {
          searchContentList.push(item)
        }
      })

      searchContentList = searchContentList.filter(item => item !== '')
      // console.log("二次切割:", searchContentList)
      return searchContentList;
    },
    // 搜索内容匹配
    matchSearchInput(dataList, searchContentList, type) {
      let matchList = [];
      // 为了性能考虑，最多只匹配这么多⬇
      let searchLimit = 20;
      try {
        dataList.forEach(item => {
          // 文字高亮匹配
          const matchResult = LightTextUtil.highlightText(item.name, searchContentList, '#E22A28');
          if (matchResult.num > 0) {
            matchList.push({
              matchNum: matchResult.num,
              name: matchResult.text,
              sourceName: item.name,
              url: item.url,
              type: type
            });
          }

          if (searchLimit <= 0) {
            throw new Error();
          }
        })
      } catch (ignore) {}

      matchList.sort((a, b) => b.matchNum - a.matchNum);
      return matchList;
    },
    // 收藏变动
    changeFavorite(value) {
      this.favoriteWebList = value.favoriteList;
      localStorage.setItem("favoriteWebList", JSON.stringify(this.favoriteWebList));
      if (value.event === 'add' || value.event === 'update') {
        FinderIQService.saveWebFavorite(value.favorite);
      }else if (value.event === 'delete') {
        FinderIQService.deleteWebFavorite(value.favorite.id);
      }else if (value.event === 'sort') {
        this.syncWebFavorites();
      }
    },
    skipFolder(value) {
      this.favoriteWebList = value.child;
    },
    // 确认选择
    confirmSelect(event) {
      window.open(event.value.url, '_blank');
    },
    // 点击空白处
    clickBlank(event) {
      console.log("点击空白处:", event)
      if (event) {
        this.searchList = []
      }
    },
    // 跟新收藏
    updateFavoriteWebList(event) {
      if (event.key === 'favoriteWebList') {
        this.favoriteWebList = JSON.parse(event.newValue);
      }
    },
    // 处理点击事件
    handleClickEvent(event) {
      const searchInput = document.getElementById('search_input');
      if ((searchInput && !searchInput.contains(event.target))) {
        console.log("触发输入框外部区域");
        this.searchList = [];
        this.aiChatRecordShow = false;
      }else if (this.aiChatRecordShow === false && this.aiChatRecordList.length > 0) {
        this.aiChatRecordShow = true;
      }
    },
    async getBookmarkList() {
      if (!this.chromeExtensionModel) return
      chrome.storage.local.get("bookmarkList", result => {
        this.bookmarkList = result.bookmarkList;
      });
    },
    async aiChat(question) {
      if (!this.ai_chat_id) {
        let response = await AiService.createNewChat();
        this.ai_chat_id = response.id
      }
      await (async () => {
        try {
          let aiChatRecord = this.aiChatRecordList[this.aiChatRecordList.length - 1];
          let answer = '';
          let searchNetData = false;

          for await (const message of AiService.chat(question, this.ai_chat_id)) {
            if (message.event === 'cmpl') { // 文字回复
              console.log("开始回答")
              answer += message.text;
              answer = answer.replace(/\[\^(\d+)\^\]/g, '<span style="background-color: #EEF0F6;color: #8F909A;padding: 0 6px;border-radius: 50px;user-select: none;margin: 0 3px;font-size: 12px">$1</span>');
              // 加上思考的图标
              aiChatRecord.answer = marked.parse(answer + `<img alt="" src="${waitIcon}" style="height: 10px; margin-top: auto" />`);
            } else if (message.event === 'search_plus') {
              console.log("联网搜索")
              if (!searchNetData) {
                aiChatRecord.searchContentFlag = true;
                aiChatRecord.searchLoading = true;
              }
              aiChatRecord.readNetData = message.msg.snippet === undefined ? aiChatRecord.readNetData : message.msg.snippet;
              searchNetData = true;
            } else if (message.event === 'loading') {
              if (message.loading === false && aiChatRecord.searchContentFlag) {
                // 网络知识搜索结束
                aiChatRecord.searchLoading = false;
                console.log("联网搜索结束")
              }
            } else if (message.event === 'all_done') {
              aiChatRecord.answer = marked.parse(answer);
              aiChatRecord.searchLoading = false;
              aiChatRecord.answerLoading = false;
              console.log("回答结束")
              this.$refs.searchInputComponentRef.aiGenerateOver();
            }
          }
          this.aiChatRecordList[this.aiChatRecordList.length - 1] = aiChatRecord;
        } catch (error) {
          console.error("Error during chat:", error);
        }
      })();
    },
    async syncWebFavorites() {
      let response = await FinderIQService.syncWebFavorites(this.favoriteWebList)
      if (response.state) {
        let data = {
          "favoriteList": response.data,
          "event": "sync",
          "favorite": null
        }
        this.changeFavorite(data)
      }
    }
  },
  mounted() {
    // 设置页面标题
    document.title = 'DToolsFinderIQ'
    // 浏览器插件模式
    this.chromeExtensionModel = window.location.protocol === 'chrome-extension:';
    // 数据初始化
    this.favoriteWebList = JSON.parse(localStorage.getItem("favoriteWebList")) || [{id: "1", name: "CLOCK", url: "CLOCK", type: "CLOCK"},{id: "2", name: "添加收藏", url: "点我添加新的收藏", type: "ADD"},{id: "3", name:"文件快传",url:"点我进行文件上传",type:"FILE"}];
    this.syncWebFavorites();
    this.getBookmarkList();
    // 监听缓存数据变化
    window.addEventListener('storage', this.updateFavoriteWebList);
    // 事件监听
    document.addEventListener('click', this.handleClickEvent);
  }
}
</script>
<style>
@font-face {
  font-family: 'OppoSans';
  src: url('../assets/fonts/OPPOSans.ttf') format('opentype');
}
body {
  margin: 0;
  height: 100vh;
  width: 100vw;
  background-image: url("@/assets/images/system/backgroundhome.png");;
  background-size: 100% 100%;
  font-family: "OppoSans", serif;
}

#logo {
  position: absolute;
  top: 35vh;
  left: 50vw;
  transform: translate(-50%, -100%);
}
#setting {
  position: absolute;
  top: 20px;
  left: 20px;
}

#search_input {
  position: absolute;
  top: calc(35vh + 10px);
  left: 50vw;
  transform: translateX(-50%);
}

#favorite_web {
  position: absolute;
  top: calc(36vh + 100px);
  //top: calc(36vh + 150px);
  left: 50vw;
  transform: translate(-50%);
  transition: opacity 300ms ease;
  width: 70%;
}

.element {
  position: absolute;
  top: 450px;
  left: 450px;
  width: 200px;
  height: 200px;
  background: rgba(255, 255, 255, 0.6);
  border: 1px solid white;
  border-radius: 10px;
  box-shadow: 2px 8px 14px 0 rgba(214, 222, 255, 0.2), 0 1px 2px 0 rgba(238, 238, 255, 1) inset, -1px -1px 3px 0 rgba(255, 255, 255, 1) inset;
  transform: rotate(-180deg); /* 旋转角度 */
}

</style>
<style scoped>

#app {
  height: 100vh;
  width: 100vw;
}

#dtools_find_my {
  height: 100%;
  width: 100%;
}
</style>